package com.platform.common.interceptor;

import com.platform.common.annotations.RoleOperation;
import com.platform.common.bean.SystemConfigBean;
import com.platform.common.menus.SysConfigEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * describe:角色操作权限拦截器
 *
 * @author rainly
 * @date 2020/4/22
 * @time 6:11 下午
 */
@Slf4j
public class RoleOperationInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        if (handler instanceof HandlerMethod) {
            final HandlerMethod handlerMethod = (HandlerMethod) handler;
            final Class<?> clazz = handlerMethod.getBeanType();
            final Method method = handlerMethod.getMethod();

            List<String> codeList = new ArrayList<>();
            if (clazz.isAnnotationPresent(RoleOperation.class)) {
                RoleOperation roleOperation = method.getAnnotation(RoleOperation.class);
                if (roleOperation != null) {
                    codeList.addAll(Arrays.asList(roleOperation.codes()));
                }
            }
            if (method.isAnnotationPresent(RoleOperation.class)) {
                RoleOperation roleOperation = clazz.getAnnotation(RoleOperation.class);
                if (roleOperation != null) {
                    codeList.addAll(Arrays.asList(roleOperation.codes()));
                }
            }

            //获得系统参数设置
            SystemConfigBean systemConfigBean = SystemConfigBean.getInstance();
            //判断权限颗粒级别，如果是 数据级别 和 功能级别 则需要校验
            boolean isNead = Objects.equals(SysConfigEnum.PermissionGrain.DATA.getValue(),systemConfigBean.getPermissionGrain()) ||
                     Objects.equals(SysConfigEnum.PermissionGrain.OPERATION.getValue(),systemConfigBean.getPermissionGrain());

            //如果需要校验
            if (isNead){
                //TODO 获得登录用户的操作功能列表
                System.out.println(codeList.size());
            }
        }
        return true;
    }
}
